package com.webserver.http;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 响应对象
 *
 * @author Chen
 */
public class HttpServletResponse {
    private Socket socket;

    /**
     * 状态代码
     */
    private int statusCode = 200;

    /**
     * 状态描述
     */
    private String statusReason = "OK";

    /**
     * 响应头相关信息
     */
    private Map<String, String> headers = new HashMap<>();

    /**
     * 响应正文对应的实体文件
     */
    private File contentFile;

    private static MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    public HttpServletResponse(Socket socket) {
        this.socket = socket;
    }

    /**
     * 发送响应
     * 用于将当前响应对象的内容以标准的HTTP响应格式发送给客户端（浏览器）
     */
    public void response() throws IOException {
        // 发送响应状态行
        sendStatusLine();
        // 发送响应头
        sendHeaders();
        // 发送响应正文
        sendContent();
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);
        out.write(10);
    }

    /**
     * 发送响应状态行
     */
    private void sendStatusLine() throws IOException {
        println("HTTP/1.1 " + statusCode + " " + statusReason);
    }

    /**
     * 发送响应头
     */
    private void sendHeaders() throws IOException {

        Set<Map.Entry<String, String>> entries = headers.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            println(key + ": " + value);
        }
        println("");
    }

    /**
     * 发送响应正文
     */
    private void sendContent() throws IOException {
        try (OutputStream out = socket.getOutputStream();
             FileInputStream fis = new FileInputStream(contentFile)
        ) {
            int len;
            byte[] buffer = new byte[1024 * 10];
            while ((len = fis.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        }
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        addHeader("Content-Type", mimetypesFileTypeMap.getContentType(contentFile));
        addHeader("Content-Length", contentFile.length() + "");
    }

    /**
     * 添加一个响应头
     *
     * @param name  响应头的名字
     * @param value 响应头对应的值
     */
    public void addHeader(String name, String value) {
        headers.put(name, value);
    }
}
